package ai.mspbots.poc.core.advise;

import ai.mspbots.poc.core.Response;
import ai.mspbots.poc.core.exception.EsException;
import ai.mspbots.poc.core.exception.ServiceException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Arrays;
import java.util.List;

@RestControllerAdvice
@Slf4j
public class ProjectRestControllerAdvise implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> converterType) {
        List<Boolean> judgeResultList = Arrays.asList(
                // ⭕判断相应的类型是否为ResultVo类型
                methodParameter.getParameterType().isAssignableFrom(Response.class),
                // ⭕判断响应的方法上是否包含 NotControllerResponseAdvice 注解
                methodParameter.hasMethodAnnotation(NotControllerResponseAdvice.class)
        );

        // 若包含其中一项,则不进行封装
        return !judgeResultList.contains(true);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // String类型不能直接包装
        if (returnType.getGenericParameterType().equals(String.class)) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                // 将数据包装在ResultVo里后转换为json串进行返回
                return objectMapper.writeValueAsString(Response.build(body));
            } catch (JsonProcessingException e) {
                // 抛出自定义的业务异常
                throw new ServiceException(-1, "返回String类型错误", e);
            }
        }

        // 否则直接包装成ResultVo返回
        return Response.build(body);
    }


    @ExceptionHandler(ServiceException.class)
    public Response<Void> handleServiceException(ServiceException e) {
        log.error("ServiceException:{}", e);
        return Response.error(e.getMessage());
    }

    @ExceptionHandler(EsException.class)
    public Response<Void> handleServiceException(EsException e) {
        log.error("EsException:{}", e);
        return Response.error(e.getMessage());
    }
}
